$(function () {
    load();
});
let table = null;
let myUrl = '/jzweb/jazUserOrder/list'
let myWhere = {},form =null;
const setMyWhere = () => {
    myWhere = {
        nameJia: $("#name").val().trim(),
        phoneJia: $("#mobile").val().trim(),
        createTime: $("#createTime").val(),
        endTime: $("#endTime").val(),
        projectId: $("#mySelect-projectId").val(),
        orderType: $("#orderType").val(),
        status: '' == $('#myRadio').val() ? null: parseInt($('#myRadio').val()),
        auditStatus:$("#auditStatus").val()
    }
}
setMyWhere()
let myCols =
    [[
        {
            field: 'number',
            title: '订单号',
            align: 'center',
        templet: function (d) {
    return   `<span>${d.number}</span>`

}
        },
        {
            field: 'nameJia',
            align: 'center',
            title: '用户名'
        },
        {
            field: 'phoneJia',
            align: 'center',
            title: '联系方式',
            templet: function (d) {
                return `<span>${d.phoneJia}</span>`

            }
        },
        // {
        //     field: 'projectName',
        //     align: 'center',
        //     title: '服务类型'
        // },
        {
            field: 'orderType',
            align: 'center',
            title: '订单类型',
            templet:(d)=>{
                return d.orderType==1?'订单':'合同'
            }
        },
        {
            field: 'orderPayType',
            title: '订单来源',
            align: 'center',
            templet: function (d) {
                return `<span>${d.orderPayType==1?'团购':d.orderPayType==0?"单独购买":'-'}</span>`

            }
        },
        // {
        //     field: 'nameYi',
        //     align: 'center',
        //     title: '阿姨姓名'
        // },
        // {
        //     field: 'phoneYi',
        //     align: 'center',
        //     title: '联系方式'
        // },
        {
            field: 'createTime',
            align: 'center',
            title: '创建时间',
            templet: function (d) {
                return   `<span>${d.createTime}</span>`

            }
        },
        {
            field: 'productName',
            align: 'center',
            title: '商品名称',
            templet: function (d) {
                return   `<span>${d.productName}</span>`

            }
        },
        {
            field: 'auditStatus',
            align: 'center',
            title: '审核状态',
            templet:function (d){
                if(d.auditStatus==""){
                    return "-"
                }
                if(d.auditStatus=="待审核"){
                    return '<span class="label label-default">待审核</span>'
                }
                if(d.auditStatus=="审核通过"){
                    return '<span class="label label-success">审核通过</span>'
                }
                if(d.auditStatus=="审核拒绝"){
                    return '<span class="label label-warning">审核拒绝</span>'
                }

            }
        },
        {
            field: 'status',
            align: 'center',
            title: '订单状态',
            templet: function (d) {
                if (d.status == '0') {
                    return '<span class="label label-default">待开始</span>'
                }
                if (d.status == '1') {
                    return '<span class="label label-info">进行中</span>'
                }
                if (d.status == '2') {
                    return '<span class="label label-success">已完成</span>'
                }
                if (d.status == '3') {
                    return '<span class="label label-warning">已取消</span>'
                }
                if (d.status == '4') {
                    return '<span class="label label-primary">已转让</span>'
                }
                return '-'

            }
        },
        {
            field: 'remark',
            align: 'center',
            title: '订单备注',
            templet: function (d) {
                return   `<span>${d.remark}</span>`

            }
        },
        {
            title: '操作',
            field: 'id',
            align: 'center',
            templet: function (d) {
                //编辑 详情
                // 只有阿姨和有权限服务转让
                // 保洁只有待开始可以编辑
                var a = `<a  class="btn btn-primary btn-sm ${look_info}" href="#" mce_href="#" title="详情" onclick="lookInfo('${d.id}','info')"><i class="fa fa-send"></i></a> `;
                var b = `<a  class="btn btn-primary btn-sm ${look_edit}" href="#" mce_href="#" title="编辑" onclick="lookInfo('${d.id}','edit')"><i class="fa fa-edit"></i></a> `;
                var c = `<a  class="btn btn-primary btn-sm ${look_serviceTransfer}" href="#" mce_href="#" title="服务转让" onclick="lookInfo('${d.id}','transferor')"><i class="fa fa-hand-o-right"></i></a> `;
                //2阿姨的
                return d.orderType==1?
                    //保洁
                    (a+ (d.status == '0'?b:'')):
                    //阿姨
                    (a+b+ (d.status != '1'?'':c))
            }
        }
    ]],
    myCols2=[[
        {
            field: 'number',
            title: '订单号',
            align: 'center',
        templet: function (d) {
    return   `<span>${d.number}</span>`

}
        },
        {
            field: 'nameJia',
            align: 'center',
            title: '用户名'
        },
        {
            field: 'phoneJia',
            align: 'center',
            title: '联系方式'
        },
        {
            field: 'projectName',
            align: 'center',
            title: '服务类型'
        },
        {
            field: 'orderType',
            align: 'center',
            title: '订单类型',
            templet:(d)=>{
                return d.orderType==1?'订单':'合同'
            }
        },
        {
            field: 'nameYi',
            align: 'center',
            title: '阿姨姓名'
        },
        {
            field: 'phoneYi',
            align: 'center',
            title: '联系方式'
        },
        {
            field: 'createTime',
            align: 'center',
            title: '创建时间',
            templet:(d)=>{
                return `<span>${d.createTime}</span>`
            }
        },
        {
            field: 'status',
            align: 'center',
            title: '订单状态',
            templet: function (d) {
                if (d.status == '0') {
                    return '<span class="label label-default">待开始</span>'
                }
                if (d.status == '1') {
                    return '<span class="label label-info">进行中</span>'
                }
                if (d.status == '2') {
                    return '<span class="label label-success">已完成</span>'
                }
                if (d.status == '3') {
                    return '<span class="label label-warning">已取消</span>'
                }
                if (d.status == '4') {
                    return '<span class="label label-primary">已转让</span>'
                }
                return '-'

            }
        },
        {
            field: 'remark',
            align: 'center',
            title: '订单备注'
        },
        {
            title: '操作',
            field: 'id',
            align: 'center',
            templet: function (d) {
                //编辑 详情
                // 只有阿姨和有权限服务转让
                // 保洁只有待开始可以编辑
                var a = `<a  class="btn btn-primary btn-sm ${look_info}" href="#" mce_href="#" title="详情" onclick="lookInfo('${d.id}','info')"><i class="fa fa-send"></i></a> `;
                var b = `<a  class="btn btn-primary btn-sm ${look_edit}" href="#" mce_href="#" title="编辑" onclick="lookInfo('${d.id}','edit')"><i class="fa fa-edit"></i></a> `;
                var c = `<a  class="btn btn-primary btn-sm ${look_serviceTransfer}" href="#" mce_href="#" title="服务转让" onclick="lookInfo('${d.id}','transferor')"><i class="fa fa-hand-o-right"></i></a> `;
                //2阿姨的
                return d.orderType==1?
                    //保洁
                    (a+ (d.status == '0'?b:'')):
                    //阿姨
                    (a+b+ (d.status != '1'?'':c))
            }
        }
    ]]
/**
 * 重置
 */
const dataReset = () => {
    $("#name").val('')
    $("#mobile").val('')
    $("#createTime").val('')
    $("#endTime").val('')
    $("#mySelect-projectId").val('')
    $("#orderType").val('')
    form.render('select');
    setMyWhere()
    table.reload('exampleTable', {
        page: {
            curr: 1 //重新从第 1 页开始
        }
        , where: myWhere,
       //重新渲染cols
        cols:$('#orderType').val()==1?myCols:myCols2
    });
}
let pages = 1;


function load() {
    layui.use(['table', 'laydate', 'form'], function () {
        table = layui.table
        var laydate = layui.laydate, $ = layui.$;
        form = layui.form;

        $('#mySelect-projectId').attr("disabled", true);
        AjaxGet('/userAunt/seleProject').then(function (response) {
            myDataList = response.data
            //设置select
            $('#mySelect-projectId').empty();
            $('#mySelect-projectId').append($('<option>', {
                value: '',
                text: '请选择订单类型'
            }))
            response.data.forEach(item => {
                $('#mySelect-projectId').append($('<option>', {
                    value: item.id,
                    text: item.name,
                    selected: item.id == $('#projectId').val()
                }))
            })
            $('#mySelect-projectId').attr("disabled", $('#type').val() == 'transferor'||$('#type').val() == 'edit');
            form.render('select');
            selectInput($('#mySelect-projectId'), 10)
        }).catch(function (error) {
            layer.msg(error.msg)
        })

        form.on('select(selectUp)', function(data){
             if(data.value==1){
                 $("#auditStatusDiv").show()
             }else {
                 $("#auditStatusDiv").hide()
             }
        });

        laydate.render({
            elem: '#ID-laydate-range',
            range: ['#createTime', '#endTime'],
            rangeLinked: true,
            type: 'datetime',
            shortcuts: [
                {
                    text: "上个月",
                    value: function () {
                        var date = new Date();
                        var year = date.getFullYear();
                        var month = date.getMonth();
                        return [
                            new Date(year, month - 1, 1),
                            new Date(year, month, 0)
                        ];
                    }
                }, {
                    text: "这个月",
                    value: function () {
                        var date = new Date();
                        var year = date.getFullYear();
                        var month = date.getMonth();
                        return [
                            new Date(year, month, 1),
                            new Date(year, month + 1, 0)
                        ];
                    }
                },
                {
                    text: "下个月",
                    value: function () {
                        var date = new Date();
                        var year = date.getFullYear();
                        var month = date.getMonth();
                        return [
                            new Date(year, month + 1, 1),
                            new Date(year, month + 2, 0)
                        ];
                    }
                }
            ],
            done: function (value, date, endDate) {
                let mydataList = value.split(' - ')
                $('#createTime').val(mydataList[0])
                $('#endTime').val(mydataList[1])
                setMyWhere()
            }
        });
        // 创建渲染实例
        table.render({
            elem: '#exampleTable'
            , id: 'exampleTable'
            , url: myUrl
            ,method:'post'
            ,contentType: 'application/json'
            , cellMinWidth: 80
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                , curr: pages //设定初始在第 5 页
                , groups: 5 //只显示 1 个连续页码
                , limit: 10
            }
            , request: {
                pageName: 'current' //页码的参数名称，默认：page
                , limitName: 'size'
            }
            , where: myWhere
            , defaultToolbar: false
            , loading: true
            , cols: $('#orderType').val()==1?myCols:myCols2
            , response: {
                statusCode: 0 //重新规定成功的状态码为 200，table 组件默认为 0
            }
            , parseData: function (res) {
                if (res.code != 0) {
                    return false;
                }
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            }
            , jump: function (obj, first) {
                //首次不执行
                if (!first) {
                    pages = obj.curr
                }
            }
            , error: function (res, msg) {
                console.log(res, msg)
            }
            , done: function (res) {
                layer.close()
            }
        });

        var $ = layui.$, active = {
            reload: function () {
                setMyWhere()
                //执行重载
                table.reload('exampleTable', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , where: myWhere,
                    //重新渲染cols
                    cols:$('#orderType').val()==1?myCols:myCols2
                });
            }
        };

        /**
         * 搜索事件
         */
        $('.demoTable .layui-btn').on('click', function () {
            var type = $(this).data('type');
            setMyWhere()
            active[type] ? active[type].call(this) : '';
        });
        form.on('radio(demo-radio-filter)', function (data) {
            $('#myRadio').val(data.elem.value)
            setMyWhere()
            table.reload('exampleTable', {
                page: {
                    curr: 1 //重新从第 1 页开始
                }
                , where: myWhere,
                //重新渲染cols
                cols:$('#orderType').val()==1?myCols:myCols2
            });
        });
    });

}

/**
 * 详情
 * @param id 数据id
 * @param index 数据集合第几个默认-1，展示全部
 */
function lookInfo(id,type) {
    const toIindex = layer.open({
        type: 2,
        title: '订单详情',
        shadeClose: false,
        resize: false,
        area: ['800px', '500px'],
        content: `/jzweb/serviceList/info/${id}/${type}`,
    });
    layer.full(toIindex);
}
